package game

import (
	"encoding/json"
	"fmt"
	"gosum/server/src/csv"
	"io/ioutil"
	"math/rand"
	"net/http"
	"os"
	"os/signal"
	"regexp"
	"sync"
	"syscall"
	"time"
)

type DBConfig struct {
	DBUser     string `json:"dbuser" `
	DBPassword string `json:"dbpassword" `
}

type ServerConfig struct {
	ServerId      int       `json:"serverid" `
	Host          string    `json:"host" `
	LocalSavePath string    `json:"localsavepath" `
	DBConfig      *DBConfig `json:"database" `
	HttpHost      string    `json:"httphost" `
}

type Server struct {
	Wg           sync.WaitGroup
	BanWordsBase []string
	Lock         *sync.RWMutex

	Config *ServerConfig
}

var server *Server

func GetServer() *Server {
	if server == nil {
		server = new(Server)
		server.Lock = new(sync.RWMutex)
	}
	return server
}

func (self *Server) Start() {
	self.LoadConfig()

	rand.Seed(time.Now().Unix())

	csv.CheckLoadCsv()

	go GetManageBanWord().Run()
	go GetManageHttp().InitData()
	go GetManagePlayer().Run()

	fmt.Println("数据测试------------------------")

	//加载配置
	//启用公共模块
	//监听客户端端口

	player := NewTestPlayer(nil, 1000001)

	go player.Run()

	go self.SignalHandle()

	//http.ListenAndServe(GetServer().Config.Host, nil)

	http.ListenAndServe("127.0.0.1:8080", nil)

	self.Wg.Wait()
	fmt.Println("服务器关闭成功!")
}

func (self *Server) Close() {
	GetManageBanWord().Close()
}

func (self *Server) AddGo() {
	self.Wg.Add(1)
}
func (self *Server) GoDone() {
	self.Wg.Done()
}

//将协程锁转移到主线程上

func (self *Server) IsBanWord(txt string) bool {
	self.Lock.RLock()
	defer self.Lock.RUnlock()
	for _, v := range self.BanWordsBase {
		match, _ := regexp.MatchString(v, txt)
		if match {
			fmt.Println("发现违禁词:", v)
		}
		if match {
			return match
		}
	}
	return false
}

func (self *Server) UpdateBanWords(banWords []string) {
	self.Lock.Lock()
	defer self.Lock.Unlock()
	self.BanWordsBase = banWords
}

func (self *Server) SignalHandle() {
	channelSignal := make(chan os.Signal)
	signal.Notify(channelSignal, syscall.SIGINT)
	for {
		select {
		case <-channelSignal:
			fmt.Println("get syscall.SIGINT")
			self.Close()
		}
	}
}

func (self *Server) LoadConfig() {
	configFile, err := ioutil.ReadFile("./config.json")
	if err != nil {
		fmt.Println("error")
		return
	}
	err = json.Unmarshal(configFile, &self.Config)
	if err != nil {
		fmt.Println("error")
		return
	}
	return
}
